package com.andong.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static com.andong.utils.SystemConstant.HS_256_KEY;
import static com.andong.utils.SystemConstant.PASSWORD_TYPE;

/**
 * ClassName: HmacSHA256Utils
 *
 * @author XHU_WHY
 * @version V1.0
 * @since 2024/1/11 20:09
 */
public class HmacSHA256Utils {
    public static String calculateHmacSHA256(String message)
            throws Exception {
        Mac hmacSHA256 = Mac.getInstance(PASSWORD_TYPE);
        SecretKeySpec secretKey = new SecretKeySpec(HS_256_KEY.getBytes(StandardCharsets.UTF_8), PASSWORD_TYPE);
        hmacSHA256.init(secretKey);
        byte[] bytes = hmacSHA256.doFinal(message.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            // 将每个字节转为16进制数存储 结果字符串的宽度为两位。如果转换后的十六进制数不足两位，则在前面用零填充。
            sb.append(String.format("%02x", b).toUpperCase());
        }
        return sb.toString();
    }
}
